import { defineStore } from 'pinia'
import { ref } from 'vue'
import { cateListService } from '@/api/cate.js'

export const useCateStore = defineStore('cate', () => {
  // 1. 响应式变量 - 分类层级数据
  const cateLevel = ref([])

  // 2. 设置分类数据
  const setCateLevel = (newCateLevel) => {
    cateLevel.value = newCateLevel
  }

  // 3. 清空分类数据
  const removeCate = () => {
    cateLevel.value = []
  }

  // 4. 刷新分类列表
  const refreshCateList = async () => {
    try {
      const { data } = await cateListService()
      setCateLevel(data)
      return data
    } catch (error) {
      console.error('刷新分类列表失败:', error)
      throw error
    }
  }

  return {
    cateLevel,
    setCateLevel,
    removeCate,
    refreshCateList // 新增的刷新方法
  }
}, {
  persist: {
    key: 'cate-storage',
    paths: ['cateLevel'],
    storage: localStorage
  }
})